﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel=Microsoft.Office.Interop.Excel;


/*参考 https://www.cnblogs.com/daviddai/archive/2013/06/10/Excel.html */
namespace ExcelInteropTest
{
    class Program
    {
        static void Main(string[] args)
        {
            KillExcel();
            xls2csv();



           





            Console.ReadKey();


        }



        static void xls2csv()
        {
            //将xls，xlsx装换成csv文件；
            Excel.Application app = new Excel.ApplicationClass();//须将嵌入互操作类型改为False
            Excel.Workbooks workbooks = app.Workbooks;
            Excel.Workbook workbook = workbooks.Open(@"C:\Users\chauncey\Desktop\test.xlsx"); ;
            workbook.SaveAs(@"C:\Users\chauncey\Desktop\test.xlsx.csv", Excel.XlFileFormat.xlCSV);
            app.ActiveWindow.Close(false);//关闭另存为文件窗口
            app.Quit();

        }


       static object[,] dt2objarray(DataTable dt)
        {
            int cnt = dt.Rows.Count;
            int columncnt = dt.Columns.Count;
            object[,] objData = new Object[cnt + 1, columncnt]; // 创建缓存数据
            // 获取列标题
            for (int i = 0; i < columncnt; i++)
            {
                objData[0, i] = dt.Columns[i].ColumnName;
            }

            // 获取具体数据
            for (int i = 0; i < cnt; i++)
            {
                DataRow dr = dt.Rows[i];
                for (int j = 0; j < columncnt; j++)
                {
                    objData[i + 1, j] = dr[j];
                }

            }

            return objData;
        }

       static void dtfillrange(DataTable dt, Excel.Range range)
       {
           range.Value2 = dt2objarray(dt);
           range.EntireColumn.AutoFit();
       }



        private static void KillExcel()
        {
            Process[] excels = Process.GetProcessesByName("EXCEL");
            foreach (var item in excels)
            {
                item.Kill();
            }
        }


    }
}
